﻿using System;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint.WebPartPages;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Collections;
using System.Web.UI.WebControls.WebParts;
using System.Globalization;
using Microsoft.SharePoint.WebControls;
using Microsoft.Web.CommandUI;

namespace beyCoo4Sharepoint.beyCooSettingsPage
{
    public partial class BeyCooSettings : System.Web.UI.Page
    {
        //variables for all controls on aspx page
        protected Button saveKeyButton;
        protected TextBox textboxCustomerKey;
        protected Panel Panel1;
        protected Image beyCooLogo;
        protected TextBox xpathPerson;
        protected TextBox xpathLocation;
        protected TextBox xpathCompany;
        protected CheckBox checkboxUseProxy;
        protected CheckBox checkboxUseCredentials;
        protected Panel panelProxy;
        protected TextBox textboxProxyAddress;
        protected TextBox textboxProxyPort;
        protected TextBox textboxProxyUser;
        protected TextBox textboxProxyPwd;
        protected Button buttonSaveProxySettings;
        //protected CheckBox checkboxUseHttpsChoice;
        protected Label labelHTTPS;
        protected XsltListViewWebPart lstvw;

        //internal variables
        private string settingsListName = "beyCoo Settings";
        private string customerKey;
        private SPWeb web = SPContext.Current.Web;
        private string settingsListGuid;
        private string beyCooPicUrl;
        //private bool httpsAvailable = true;
        private Hashtable availableServices = new Hashtable();


        protected override void OnLoad(EventArgs e)
        {
            beyCooPicUrl = SPContext.Current.Web.Url + "/_layouts/images/BeyCooEvent/beyCoo_posterous_logo2.jpg";
            beyCooLogo.ImageUrl = beyCooPicUrl;
            base.OnLoad(e);
        }


        protected override void CreateChildControls()
        {
            //event handler save button for customerkey init
            saveKeyButton.Click += new EventHandler(saveKeyButton_Click);
            
            //event handler save button for proxy init
            buttonSaveProxySettings.Click += new EventHandler(buttonSaveProxySettings_Click);
            
            //init check if customerkey was already saved, when yes: load it into text box
            if (web.Properties.ContainsKey(beyCooConstants.beyCooCustomerKey))
            {
                textboxCustomerKey.Text = web.Properties[beyCooConstants.beyCooCustomerKey].ToString();
            }
            //same for checkboxUseProxy
            if (web.Properties.ContainsKey(beyCooConstants.beyCooUseProxy))
            {
                checkboxUseProxy.Checked = Boolean.Parse(web.Properties[beyCooConstants.beyCooUseProxy].ToString());
            }
            checkboxUseProxy.AutoPostBack = true;
            checkboxUseProxy.CheckedChanged += new EventHandler(checkboxUseProxy_CheckedChanged);

            //init values for checkboxUseProxy
            if (checkboxUseProxy.Checked)
            {
                if (web.Properties.ContainsKey(beyCooConstants.beyCooProxyAddress))
                {
                    textboxProxyAddress.Text = web.Properties[beyCooConstants.beyCooProxyAddress].ToString();
                }
                if (web.Properties.ContainsKey(beyCooConstants.beyCooProxyPort))
                {
                    textboxProxyPort.Text = web.Properties[beyCooConstants.beyCooProxyPort].ToString();
                }
                if (web.Properties.ContainsKey(beyCooConstants.beyCooUseProxyCredentials))
                {
                    checkboxUseCredentials.Checked = Boolean.Parse(web.Properties[beyCooConstants.beyCooUseProxyCredentials].ToString());
                }
                //init checkboxUseCredentials
                checkboxUseCredentials.AutoPostBack = true;
                checkboxUseCredentials.CheckedChanged += new EventHandler(checkboxUseCredentials_CheckedChanged);

                if (checkboxUseCredentials.Checked)
                {
                    //init values for checkboxUseCredentials
                    if (web.Properties.ContainsKey(beyCooConstants.beyCooProxyUser))
                    {
                        textboxProxyUser.Text = web.Properties[beyCooConstants.beyCooProxyUser].ToString();
                    }
                    if (web.Properties.ContainsKey(beyCooConstants.beyCooProxyPwd))
                    {
                        textboxProxyPwd.Text = web.Properties[beyCooConstants.beyCooProxyPwd].ToString();
                    }
                    textboxProxyUser.Visible = true;
                    textboxProxyPwd.Visible = true;
                }
                else
                {
                    textboxProxyUser.Visible = false;
                    textboxProxyPwd.Visible = false;
                }

                panelProxy.Visible = true;
            }
            else 
            { 
                panelProxy.Visible = false; 
            }

            //filling the settings list "list name" field with the available lists for this SP environment
            SPList lst = web.Lists[settingsListName];
            SPFieldChoice dropDownListName = (SPFieldChoice)lst.Fields["List name"];
            dropDownListName.Choices.Clear(); //Clears out the list of options

            foreach (SPList list in web.Lists)
            {
                if ((!list.Title.Equals(settingsListName)) && (!list.Title.Equals("TaxonomyHiddenList")))
                {
                    dropDownListName.Choices.Add(list.Title.ToString());
                }
            }
            web.AllowUnsafeUpdates = true;
            dropDownListName.Update(); //Need to update the column for the changes to take effect     
            web.AllowUnsafeUpdates = false;


            settingsListGuid = SPContext.Current.Web.Lists[settingsListName].ID.ToString();
            lstvw.ListName = new Guid(settingsListGuid).ToString();
            lstvw.ListId = new Guid(settingsListGuid);
            lstvw.AllowEdit = true;
            lstvw.ViewGuid = SPContext.Current.Web.Lists[settingsListName].DefaultView.ID.ToString();

            lstvw.AllowConnect = true;

            //init checkboxUseHttpsChoice
            //checkboxUseHttpsChoice.AutoPostBack = true;
            //checkboxUseHttpsChoice.CheckedChanged += new EventHandler(checkboxUseHttpsChoice_CheckedChanged);
            //if (web.Properties.ContainsKey(beyCooConstants.beyCooUseHttpsChoice))
            //{
            //    checkboxUseHttpsChoice.Checked = Boolean.Parse(web.Properties[beyCooConstants.beyCooUseHttpsChoice].ToString());
            //}
            
            //filling the settings list "service" field with the available services (service plans) for this customer key
            SPFieldChoice dropDownService = (SPFieldChoice)lst.Fields[beyCooConstants.settingsListColService];
            dropDownService.Choices.Clear(); //Clears out the list of options
            
            //call getServices to retrieve available services for this customerkey, and at the same time, check certificate when https is requested            
            if (textboxCustomerKey.Text.Length > 0)
            {
                FillServicesAndSetCertLabel();
            }
            else 
            {
                labelHTTPS.Text = "<p style=\"color: #008000\">Please enter a customerkey to check the connection</p> ";
            }
                        
            // fill servicekeys out of resulting hashtable
            foreach (DictionaryEntry service in availableServices)
            {
                dropDownService.Choices.Add(service.Key.ToString());
            }

            web.AllowUnsafeUpdates = true;
            dropDownService.Update(); //Need to update the column for the changes to take effect     
            web.AllowUnsafeUpdates = false;

            //base.CreateChildControls();
        }

        /// <summary>
        /// call getServices to retrieve available services for this customerkey, and at the same time, check certificate when https is requested
        /// </summary>
        private void FillServicesAndSetCertLabel()
        {
            //get the serviceURLs and complete them
            string serviceURL = beyCooConstants.beyCooServiceURL + textboxCustomerKey.Text + "/services.xml";
            string serviceURLhttps = beyCooConstants.beyCooServiceURLhttps + textboxCustomerKey.Text + "/services.xml";
            string serverName = web.Url;
            //get available services over a webrequest
            beyCooConnection beycooCon = new beyCooConnection();


            //get available services from the webservice for this customerkey, check to see if https is available, when not, use http 
            //and set boolean "beyCooUseHttps" to false
            if (true)
            {
                availableServices = beycooCon.getServices(serviceURLhttps, serverName, web);
                string httpsAvailable = web.Properties[beyCooConstants.beyCooHttpsAvailable].ToString();

                if (httpsAvailable.Equals("true"))
                {
                    //set the label on the settings page with info about https availability
                    labelHTTPS.Text = "<p style=\"color: #008000\">SSL/HTTPS secured connection is available</p> ";
                }
                else if (httpsAvailable.Equals("nottrusted"))
                {
                    //httpsAvailable = true;
                    //set the label on the settings page with info about https availability
                    labelHTTPS.Text = "<p style=\"color: #FF6600\">Warning: Certificate is not trusted</p> ";
                }
                else if (httpsAvailable.Equals("false"))
                {
                    //set the label on the settings page with info about https availability
                    labelHTTPS.Text = "<p style=\"color: #FF0000\">Error: Webservice not available</p> ";
                }

            }
            ////checkboc not checked, so just go over HTTP, HTTPS is not used
            //else
            //{
            //    availableServices = beycooCon.getServices(serviceURL, serverName);
            //    //httpsAvailable = false;
            //    //set the label on the settings page with info about https availability
            //    labelHTTPS.Text = "<p style=\"color: #FF6600\">HTTPS is currently not selected</p> ";
            //}
        }


        //void checkboxUseHttpsChoice_CheckedChanged(object sender, EventArgs e)
        //{
        //    FillServicesAndSetCertLabel();
        //}


        void checkboxUseProxy_CheckedChanged(object sender, EventArgs e)
        {
            setSetting(beyCooConstants.beyCooUseProxy, checkboxUseProxy.Checked.ToString());
            //show or hide proxy panel
            if (checkboxUseProxy.Checked)
            {
                if (web.Properties.ContainsKey(beyCooConstants.beyCooProxyAddress))
                {
                    textboxProxyAddress.Text = web.Properties[beyCooConstants.beyCooProxyAddress].ToString();
                }
                if (web.Properties.ContainsKey(beyCooConstants.beyCooProxyPort))
                {
                    textboxProxyPort.Text = web.Properties[beyCooConstants.beyCooProxyPort].ToString();
                }
                if (web.Properties.ContainsKey(beyCooConstants.beyCooUseProxyCredentials))
                {
                    checkboxUseCredentials.Checked = Boolean.Parse(web.Properties[beyCooConstants.beyCooUseProxyCredentials].ToString());
                }

                checkboxUseCredentials.AutoPostBack = true;
                checkboxUseCredentials.CheckedChanged += new EventHandler(checkboxUseCredentials_CheckedChanged);

                if (checkboxUseCredentials.Checked)
                {
                    if (web.Properties.ContainsKey(beyCooConstants.beyCooProxyUser))
                    {
                        textboxProxyUser.Text = web.Properties[beyCooConstants.beyCooProxyUser].ToString();
                    }
                    if (web.Properties.ContainsKey(beyCooConstants.beyCooProxyPwd))
                    {
                        textboxProxyPwd.Text = web.Properties[beyCooConstants.beyCooProxyPwd].ToString();
                    }
                    textboxProxyUser.Visible = true;
                    textboxProxyPwd.Visible = true;
                }
                else
                {
                    textboxProxyUser.Visible = false;
                    textboxProxyPwd.Visible = false;
                }

                panelProxy.Visible = true;
            }
            else { panelProxy.Visible = false; }
        }

        void checkboxUseCredentials_CheckedChanged(object sender, EventArgs e)
        {
            setSetting(beyCooConstants.beyCooUseProxyCredentials, checkboxUseCredentials.Checked.ToString());

            if (checkboxUseCredentials.Checked)
            {
                if (web.Properties.ContainsKey(beyCooConstants.beyCooProxyUser))
                {
                    textboxProxyUser.Text = web.Properties[beyCooConstants.beyCooProxyUser].ToString();
                }
                if (web.Properties.ContainsKey(beyCooConstants.beyCooProxyPwd))
                {
                    textboxProxyPwd.Text = web.Properties[beyCooConstants.beyCooProxyPwd].ToString();
                }
                textboxProxyUser.Visible = true;
                textboxProxyPwd.Visible = true;
            }
            else
            {
                textboxProxyUser.Visible = false;
                textboxProxyPwd.Visible = false;
            }
        }

        void saveKeyButton_Click(object sender, EventArgs e)
        {
            //get settings from the front end and save them to the propertybag   
            customerKey = textboxCustomerKey.Text;
            setSetting(beyCooConstants.beyCooCustomerKey, customerKey);
            CreateChildControls();

        }

        void buttonSaveProxySettings_Click(object sender, EventArgs e)
        {
            setSetting(beyCooConstants.beyCooProxyAddress, textboxProxyAddress.Text);
            setSetting(beyCooConstants.beyCooProxyPort, textboxProxyPort.Text);
            setSetting(beyCooConstants.beyCooProxyUser, textboxProxyUser.Text);
            setSetting(beyCooConstants.beyCooProxyPwd, textboxProxyPwd.Text);
        }


        private void setSetting(string key, string value)
        {
            if (!web.Properties.ContainsKey(key))
            {
                web.Properties.Add(key, value);
            }
            else
            {
                web.Properties[key] = value;
            }
            web.Properties.Update();
        }




    }
}
